#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 19-6-23 上午11:28
# @Author  : Tom
# @Site    : 查询搜索用户，并手动新增用户
# @File    : users.py
# @Software: PyCharm
from django.conf import settings

# 接口分析
# 请求方式： get
# 请求路径: /meiduo_admin/users/?page=1&pagesize=10&keyword=
# 请求参数： page pagesize keyword
# 返回结果：
# {
#     "counts": "用户总量",
#     "lists": [
#         {
#             "id": "用户id",
#             "username": "用户名",
#             "mobile": "手机号",
#             "email": "邮箱"
#         },
#         ...
#     ],
#     "page": "页码",
#     "pages": "总页数",
#     "pagesize": "页容量"
# }


# 逻辑分析：
# 接受数据：
# 写好序列化器，指定序列化器和查询集，
# 分页，查询
# 按照前端的数据返回结果
from rest_framework.generics import ListCreateAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response

from meiduo_admin.serilizers import UserSerializer
from meiduo_admin.utils import PageNumber_User
from users.models import User
from rest_framework.mixins import CreateModelMixin,UpdateModelMixin,DestroyModelMixin,RetrieveModelMixin,ListModelMixin


# 对用户的增加和分页查询，搜索
class UserView(ListCreateAPIView):
    # 指定序列化器和查询集
    serializer_class = UserSerializer
    # queryset = User.objects.all()
    # 指定分页器
    pagination_class = PageNumber_User
    permission_classes = [IsAdminUser, ]

    # 制定查询集
    def get_queryset(self):
        # 获取关键词 , queryset必须为查询列表，不能单为对象
        keyword = self.request.query_params.get("keyword")
        if keyword == "" or keyword is None:
            # queryset = User.objects.get_queryset().order_by("id")
            queryset = User.objects.order_by("id")
        else:
            queryset = User.objects.filter(username=keyword)
            if len(queryset) == 0:
                queryset = User.objects.filter(mobile=keyword)
            if len(queryset) == 0:
                queryset = User.objects.filter(email=keyword)
            if len(queryset) == 0:
                queryset = User.objects.filter(id=keyword)
        return queryset
